<?php
/**
 * Created by PhpStorm.
 * User: mars
 * Date: 2019/1/24
 * Time: 1:30 PM
 */

namespace api\controllers;


use abei2017\wx\Application;
use abei2017\wx\mini\payment\Pay;
use api\models\event\OrderEvent;
use api\models\Good;
use api\models\Order;
use api\models\search\OrderSearch;
use api\models\User;
use yii\debug\models\search\Debug;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\web\BadRequestHttpException;
use yii\web\NotFoundHttpException;
use yii\web\ServerErrorHttpException;
use Yii;

class OrderController extends BaseController
{

    public $enableCsrfValidation = false;

    public $modelClass = "\api\models\Order";

    public function init()
    {
        $this->on(Order::EVENT_PAY_SUCCESS, [Order::className(), 'paySuccess']);
        parent::init();

    }

    public function actions()
    {
        $actions          = parent::actions();
        $actions['index'] = [
            'class'               => 'yii\rest\IndexAction',
            'modelClass'          => $this->modelClass,
            'checkAccess'         => [$this, 'checkAccess'],
            'prepareDataProvider' => function ($action, $filter) {
                $model = new OrderSearch();

                return $model->search(['uid' => Yii::$app->getUser()->id]);
            }
        ];

        return $actions;
    }


    /*
     * POST
     *
     * 订单支付
     * 不负责生成订单
     *
     * out_trade_no
     *
     *
     *
     * */
    public function actionOrder()
    {
        $date = \Yii::$app->getRequest()->getBodyParams();

//        $order = new Order();
//        $order->load($date, '');
//        $order->uid         = \Yii::$app->getUser()->id;
//        $order->total_price = $order->good->price * $order->number;
//        $order->order_id    = uniqid();
//        if ($order->save()) {
//            throw new ServerErrorHttpException('Failed to create the object for unknown reason.');
//        }
//        return "oirder pay";
        $order = Order::findOne(['order_id' => $date['out_trade_no']]);
        if ($order == null) {
            throw new NotFoundHttpException('不存在此订单，核对out_trade_no');
        }
        if ($order->status == Order::STATUS_PAY_SUCCESS) {
            throw new ServerErrorHttpException("订单已支付");
        }
        /** @var Pay $pay */

        $pay        = (new Application())->driver("mini.pay");
        $attributes = [
            'body'         => $order->good->title,
            'out_trade_no' => $order->order_id,
//            'total_fee'    => $order->total_price * 100,
            'total_fee'    => $order->total_price,
            'notify_url'   => Yii::$app->urlManager->createAbsoluteUrl(['notify']),
            'openid'       => User::findOne(Yii::$app->getUser()->id)->wx_openid,
        ];
        $jsApi = $pay->jsApi($attributes);
//        var_dump($jsApi);

        if ($jsApi->return_code == 'SUCCESS' && $jsApi->result_code == 'SUCCESS') {
            $prepayId = $jsApi->prepay_id;
            $result   = $pay->configForPayment($prepayId);
            Yii::$app->getResponse()->setStatusCode(200);
            return [
                'result' => $result
            ];
        } else {
            throw new ServerErrorHttpException('Failed to get return_code,something wrong.');
        }
    }


    public function actionNotify()
    {
        $pay      = (new Application())->driver("mini.pay");
        $response = $pay->handleNotify(function ($notify, $isSuccess) {
//            Yii::warning($isSuccess);
            if ($isSuccess) {
                @list($type, $id, $_) = explode('-', $notify['out_trade_no']);
                $order        = new OrderEvent();
//                Yii::warning($notify['out_trade_no']);
                $order->order = Order::findOne(['order_id' => $notify['out_trade_no']]);
                $this->trigger(Order::EVENT_PAY_SUCCESS, $order); //触发支付完成事件
                return true;
            }
            return false;
        });

        return $response;
    }

    /**
     * @return Order|null
     * @throws \yii\base\InvalidConfigException
     */
    public function actionOrderTest()
    {
        $date  = \Yii::$app->getRequest()->getBodyParams();
        $order = new Order();
        $order->load($date, '');
//        var_dump($order);
        $order->uid         = \Yii::$app->getUser()->id;
        $order->total_price = $order->good->price * $order->number;
        $order->order_id    = uniqid();
        if ($order->save()) {
            throw new ServerErrorHttpException('Failed to create the object for unknown reason.');
        }

        return $order;
    }


    public function actionNotifyTest($out_trade_no)
    {

        $order = Order::findOne(['order_id' => $out_trade_no]);
//        return $order;
        $event        = new OrderEvent();
        $event->order = $order;
        $this->trigger(Order::EVENT_PAY_SUCCESS, $event);

    }


}